package com.neu.controller;

import com.alibaba.excel.EasyExcel;
import com.neu.base.PageBean;
import com.neu.base.Result;
import com.neu.config.DataListenerFactory;
import com.neu.entity.Tenant;
import com.neu.entity.security.LoginUser;
import com.neu.service.TenantService;
import com.neu.utils.excel.DataListener;
import com.neu.utils.excel.ExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/tenants")
@Tag(name = "租户管理")
public class TenantController {
    @Autowired
    TenantService tenantService;

    @Autowired
    private DataListenerFactory dataListenerFactory;

    @PostMapping("/page")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", required = true),
            @Parameter(name = "pageSize", description = "每页显示数量", required = true)
    })
    @Operation(summary = "分页查询")
    public Result page(@RequestParam Integer pageNum,
                       @RequestParam Integer pageSize){

        PageBean<Tenant> pagelist = tenantService.pagelist(pageNum, pageSize);
        //如果当前页码值大于总页数，返回最后一页数据
        if (pageNum > pagelist.getTotalPage()) {
            pagelist = tenantService.pagelist((int)pagelist.getTotalPage(), pageSize);
        }
        return Result.success(pagelist);
    }

    @GetMapping("/all")
    @Operation(summary = "获取所有租户")
    public Result all(){
        List<Tenant> list=tenantService.all();
        return Result.success(list);
    }

    @PostMapping("/findById")
    @Operation(summary = "根据id查询租户")
    public Result findById(@RequestParam String tenantId){
        // @RequestParam 来接收 URL 参数
        return Result.success(tenantService.getById(tenantId));
    }

    @PostMapping("/update")
    @Operation(summary = "更新租户")
    public Result update(@RequestBody Tenant tenant){
        // @RequestBody 用于接收前端传递给后端的json字符串中的数据
        //获取当前登录用户id
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        tenant.setUpdateId(user.getUserId());
        tenant.setUpdateTime(LocalDateTime.now());
        return Result.success(tenantService.updateById(tenant));
    }

    @PostMapping("/search")
    @Operation(summary = "搜索租户")
    public Result search(
            @RequestBody Map map){
        PageBean<Tenant> pagelist =tenantService.search(map);
        return Result.success(pagelist);
    }

    @PostMapping("/contactIds")
    @Operation(summary = "联系人列表")
    public Result contactIds(){
        List<String> contactIds =tenantService.contactIds();
        return Result.success(contactIds);
    }

    @PostMapping("/add")
    @Operation(summary = "添加租户")
    public Result add(@RequestBody Tenant tenant){
        tenant.setDelFlag("1");
        tenant.setCreateTime(LocalDateTime.now());
        tenant.setExpireTime(LocalDateTime.now().plusDays(30));//默认一个月后到期
        tenant.setRights("1");

        //获取当前登录用户id
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = user.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")) {
            return Result.error("无权限添加租户!");
        }
        tenant.setCreateId(user.getUserId());

        //创建即为最近一次更新
        tenant.setUpdateId(tenant.getCreateId());
        tenant.setUpdateTime(tenant.getCreateTime());

        return Result.success(tenantService.save(tenant));
    }

    @PostMapping("/delete")
    @Operation(summary = "删除租户")
    public Result delete(@RequestBody Tenant tenant){
        //获取当前登录用户id
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = user.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")) {
            return Result.error("无权限删除租户!");
        }
        return tenantService.removeTenant(tenant.getTenantId());
    }

    @PostMapping("/deleteBatch")
    @Operation(summary = "批量删除租户")
    public Result deleteBatch(@RequestBody String[] ids){
        //获取当前登录用户id
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = user.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")) {
            return Result.error("无权限删除租户!");
        }
        return tenantService.removeTenantBatch(Arrays.asList(ids));
    }

    @PostMapping("/import")
    @Operation(summary = "导入租户信息")
    public Result importTenants(@RequestParam("file") MultipartFile file) {
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = user.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")) {
            return Result.error("无权限导入租户!");
        }
        if (file.isEmpty()) {
            return Result.error("上传的文件为空");
        }

        try (InputStream inputStream = file.getInputStream()) {
            // 创建监听器
            DataListener<Tenant> listener = dataListenerFactory.createTenantListener();

            // 读取 Excel
            EasyExcel.read(inputStream, Tenant.class,listener).sheet().doRead();

            // 获取读取的数据
            List<Tenant> tenantList = listener.getCachedDataList();

            return Result.success("导入成功，导入条数: " + tenantList.size());
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入过程中出现错误: " + e.getMessage());
        }
    }

    @GetMapping("/export")
    @Operation(summary = "导出租户信息")
    public void export(HttpServletResponse response){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        String fileName ="";
        if (!permissions.contains("ROLE_super")) {
            fileName = loginUser.getTenantName()+"租户信息表.xlsx";// 下载时的文件名
        }else{
            fileName = "所有租户信息表.xlsx";// 下载时的文件名
        }
        String sheetName = "租户信息"; // 工作表名称
        List<Tenant> tenants = tenantService.all();
        // 调用工具类进行导出
        ExcelUtil.exportExcel(response, fileName, sheetName, Tenant.class, tenants);
    }
}
